<template>
  <div class="view-fill">
    <div class="app-container-flex">
      <FullScreen
        v-model="showDialog"
        :title="title"
        @returnBack="$emit('returnModify')"
      >
        <template v-slot:full-button>
          <el-button @click="save()">保存</el-button>
        </template>
        <div class="model-panel">
          <div class="model-panel-title">
            <p>{{ $t('basic_information') }}</p>
          </div>
          <div class="model-panel-body">
            <!-- form -->
            <PageForm
              class="paddingBox order-model-formBox flex_wrap_start_start"
              v-model:ref-obj="formInfo.ref"
              :disabled="formInfo.disabled"
              :data="formInfo.data"
              :field-list="formInfo.fieldList"
              :rules="formInfo.rules"
              :label-width="formInfo.labelWidth"
            >
              <template v-slot:form-deptName>
                <el-input
                  v-model="formInfo.data.deptName"
                  class="not-mongolia"
                  type="input"
                  :required="true"
                  :disabled="true"
                  :placeholder="'请选择分析部门'"
                >
                  <template #append>
                    <el-icon @click="checkDeptName"><MoreFilled /></el-icon>
                  </template>
                </el-input>
              </template>
            </PageForm>
          </div>
        </div>
        <div class="model-panel">
          <div class="model-panel-title">
            <p>分析设备详细信息</p>
          </div>
          <div class="model-panel-body">
            <!-- 条件栏 -->
            <PageFilter :filter-list="filterInfo.list">
              <template v-slot:filter-addAsset>
                <el-button :disabled="!canAddAsset" @click="addAsset()"
                  >添加设备</el-button
                >
              </template>
              <template v-slot:filter-removeAsset>
                <el-button :disabled="!canRemoveAsset" @click="removeAsset()"
                  >删除设备</el-button
                >
              </template>
              <template v-slot:filter-btnSlotArr>
                <el-form
                  :inline="true"
                  :model="formFilter"
                  class="demo-form-inline"
                >
                  <el-form-item label="预计检查(治疗)人次/月：">
                    <el-input-number
                      v-model.lazy="formFilter.estimateTreatPersonTime"
                      clearable
                      controls-position="right"
                      :disabled="!canSettingAsset"
                      :precision="0"
                      :min="0"
                      :max="99999999"
                    />
                  </el-form-item>
                  <el-form-item label="预计检查(治疗)收入/月：">
                    <el-input-number
                      v-model.lazy="formFilter.estimateTreatIncome"
                      clearable
                      controls-position="right"
                      :disabled="!canSettingAsset"
                      :precision="
                        $store.state.permission.systemConfig
                          .assets_price_precision
                      "
                      :min="0"
                      :max="99999999"
                    />
                  </el-form-item>
                  <el-form-item label="预计开机时长/月: ">
                    <el-input-number
                      v-model.lazy="formFilter.estimatePowerUp"
                      clearable
                      controls-position="right"
                      :disabled="!canSettingAsset"
                      :precision="0"
                      :min="0"
                      :max="99999999"
                    />
                  </el-form-item>
                  <el-form-item>
                    <el-button
                      :disabled="!canSettingAsset"
                      type="primary"
                      @click="allSetting"
                      >一键设置</el-button
                    >
                  </el-form-item>
                </el-form>
              </template>
            </PageFilter>
            <div class="flex_full_item">
              <el-form ref="tableForm" :model="tableInfo" style="width: 100%">
                <!-- 表格 -->
                <PageTable
                  :refresh="tableInfo.refresh"
                  :init-curpage="tableInfo.initCurpage"
                  v-model:data="tableInfo.data"
                  :pager="false"
                  :tab-index="true"
                  :field-list="tableInfo.fieldList"
                  :handle="tableInfo.handle"
                  :row-class-name="tableRowClassName"
                  :isRowClickSelect="true"
                  :isDynamic="true"
                  @handleEvent="handleEvent"
                >
                  <template v-slot:col-amortizationRate="scope">
                    <el-form-item
                      v-if="scope.$index >= 0"
                      :prop="`data.${scope.$index}.amortizationRate`"
                      :rules="[
                        {
                          required: true,
                          message: '请输入收入/成本摊销比例(%)',
                          trigger: ['blur', 'change'],
                        },
                      ]"
                      @click.stop=""
                    >
                      <el-input-number
                        style="width: 100%"
                        v-model.lazy="scope.row.amortizationRate"
                        clearable
                        controls-position="right"
                        :precision="2"
                        :min="0"
                        :max="100"
                        :disabled="!canAmortizationRate"
                        @input="
                          changeValidate(
                            $event,
                            `data.${scope.$index}.amortizationRate`,
                            'tableForm'
                          )
                        "
                      />
                    </el-form-item>
                  </template>
                  <template v-slot:col-estimateTreatPersonTime="scope">
                    <el-form-item
                      v-if="scope.$index >= 0"
                      :prop="`data.${scope.$index}.estimateTreatPersonTime`"
                      :rules="[
                        {
                          required: true,
                          message: '请输入预计检查(治疗)人次/月',
                          trigger: ['blur', 'change'],
                        },
                      ]"
                      @click.stop=""
                    >
                      <el-input-number
                        style="width: 100%"
                        v-model.lazy="scope.row.estimateTreatPersonTime"
                        clearable
                        controls-position="right"
                        :precision="0"
                        :min="0"
                        :max="99999999"
                        @input="
                          changeValidate(
                            $event,
                            `data.${scope.$index}.estimateTreatPersonTime`,
                            'tableForm'
                          )
                        "
                      />
                    </el-form-item>
                  </template>
                  <template v-slot:col-estimateTreatIncome="scope">
                    <el-form-item
                      v-if="scope.$index >= 0"
                      :prop="`data.${scope.$index}.estimateTreatIncome`"
                      :rules="[
                        {
                          required: true,
                          message: '请输入预计检查(治疗)收入/月',
                          trigger: ['blur', 'change'],
                        },
                      ]"
                      @click.stop=""
                    >
                      <el-input-number
                        style="width: 100%"
                        v-model.lazy="scope.row.estimateTreatIncome"
                        clearable
                        controls-position="right"
                        :precision="
                          $store.state.permission.systemConfig
                            .assets_price_precision
                        "
                        :min="0"
                        :max="99999999"
                        @input="
                          changeValidate(
                            $event,
                            `data.${scope.$index}.estimateTreatIncome`,
                            'tableForm'
                          )
                        "
                      />
                    </el-form-item>
                  </template>
                  <template v-slot:col-estimatePowerUp="scope">
                    <el-form-item
                      v-if="scope.$index >= 0"
                      :prop="`data.${scope.$index}.estimatePowerUp`"
                      :rules="[
                        {
                          required: true,
                          message: '请输入预计开机时长/月',
                          trigger: ['blur', 'change'],
                        },
                      ]"
                      @click.stop=""
                    >
                      <el-input-number
                        style="width: 100%"
                        v-model.lazy="scope.row.estimatePowerUp"
                        clearable
                        controls-position="right"
                        :precision="0"
                        :min="0"
                        :max="99999999"
                        @input="
                          changeValidate(
                            $event,
                            `data.${scope.$index}.estimatePowerUp`,
                            'tableForm'
                          )
                        "
                      />
                    </el-form-item>
                  </template>
                </PageTable>
              </el-form>
            </div>
          </div>
        </div>
      </FullScreen>
    </div>
    <!-- 添加资产 -->
    <SelectAsset
      v-if="selectAssetInfo.visible"
      v-model:show-dialog="selectAssetInfo.visible"
      :query="selectAssetInfo.query.queryMap"
      :query-params="selectAssetInfo.query.queryParams"
      table-key="analysisPlanAddCoreAsset-com.slip.spd.entity.vo.core.CoreAssetVO"
      :check-box="selectAssetInfo.checkBox"
      :highlightRow="true"
      @callback="callBackAsset"
    />
    <!-- 选择部门 -->
    <SelectDept
      v-if="useDeptInfo.visible"
      v-model:show-dialog="useDeptInfo.visible"
      :check-box="false"
      :highlight-row="true"
      :query="useDeptInfo.query"
      :save-empty="true"
      @callback="callbackUseDept"
    />
  </div>
</template>

<script setup name="assetAnalysisPlansModify">
import {
  postAnalysisPlan,
  putAnalysisPlan,
  getAnalysisPlanById,
  getAnalysisPlanDetailById,
} from '@/api/asset'
const { proxy } = getCurrentInstance()
const props = defineProps(['visible', 'title', 'orderId'])

const systemConfig = ref(proxy.$store.state.permission.systemConfig)
//表单相关
const formInfo = ref({
  ref: null,
  data: {},
  fieldList: [
    {
      label: '分析方案名称',
      value: 'planName',
      type: 'input',
    },
    {
      label: '分析部门',
      value: 'deptName',
      type: 'slot',
      required: true,
    },
    {
      label: '分析类型',
      value: 'analysisType',
      type: 'select-model',
      code: 'analysis_type',
      required: true,
    },
    {
      label: '收入/成本摊销方式',
      value: 'amortizationMethod',
      type: 'select-model',
      code: 'amortization_method',
      required: true,
      show: true,
    },
  ],
  rules: {
    planName: [
      {
        required: true,
        message: '请输入分析方案名称',
        trigger: 'blur',
      },
    ],
    deptName: [
      {
        required: true,
        message: '请选择分析部门',
        trigger: 'change',
      },
    ],
  },
  labelWidth: '180px',
})
// 过滤相关配置
const filterInfo = ref({
  query: {},
  list: [
    { type: 'slot', value: 'addAsset' },
    { type: 'slot', value: 'removeAsset' },
    { type: 'slot', value: 'btnSlotArr' },
  ],
})
// 一键设置表单
const formFilter = ref({})
// 表格相关
const tableInfo = ref({
  refresh: 1,
  initCurpage: 1,
  data: [],
  selections: [],
  fieldList: [
    {
      label: '资产卡片号',
      value: 'assetCode',
    },
    {
      label: '资产名称',
      value: 'assetName',
    },
    { label: '规格', value: 'standard' },
    { label: '厂家', value: 'brandName' },
    { label: '供应商', value: 'supplierName' },
    {
      label: '收入/成本摊销比例(%)',
      value: 'amortizationRate',
      type: 'slot',
      width: '180px',
      disabled: true,
    },
    {
      label: '预计检查(治疗)人次/月',
      value: 'estimateTreatPersonTime',
      type: 'slot',
      width: '180px',
    },
    {
      label: '预计检查(治疗)收入/月',
      value: 'estimateTreatIncome',
      type: 'slot',
      width: '180px',
    },
    {
      label: '预计开机时长/月',
      value: 'estimatePowerUp',
      type: 'slot',
      width: '180px',
    },
  ],
  handle: {
    fixed: 'right',
    label: '操作',
    width: '50',
    btList: [
      {
        label: '删除',
        event: removeAsset,
        popconfirmText: '删除后将改变数据,是否继续？',
        show: true,
      },
    ],
  },
})
const selectAssetInfo = ref({
  visible: false,
  checkBox: true,
  query: {
    queryMap: {
      id: {
        queryType: 'NOT_IN',
        queryCategory: 'AND',
        value: '',
      },
      assetStatus: {
        queryType: 'IN',
        queryCategory: 'AND',
        value: '1,3',
      },
      status: {
        queryType: 'IN',
        queryCategory: 'AND',
        value: '3',
      },
    },
    queryParams: {
      assetAnalysisFilter: 1,
      deptId: '',
      analysisPlanIdNotIn: '',
    },
  },
})
const useDeptInfo = ref({
  visible: false,
  query: {
    status: 1,
    deptAuth: 'id',
  },
})

const showDialog = computed({
  get() {
    return props.visible
  },
  set(val) {
    proxy.$emit('update:visible', val) // 更新父组件visible
  },
})
const canSave = computed(() => {
  return tableInfo.value.data.length
})
const canAddAsset = computed(() => {
  if (
    formInfo.value.data.analysisType == 0 &&
    tableInfo.value.data.length === 1
  ) {
    return false
  }
  return formInfo.value.data.deptId
})
const canRemoveAsset = computed(() => {
  return tableInfo.value.selections.length
})
const canSettingAsset = computed(() => {
  return tableInfo.value.data.length
})
const canAmortizationRate = computed(() => {
  return (
    formInfo.value.data.analysisType != 0 &&
    formInfo.value.data.amortizationMethod == 2
  )
})

watch(
  () => formInfo.value.data.analysisType,
  (val) => {
    if (val == 0) {
      formInfo.value.fieldList.forEach((item) => {
        if (item.value === 'amortizationMethod') {
          item.show = false
        }
      })
    } else {
      formInfo.value.fieldList.forEach((item) => {
        if (item.value === 'amortizationMethod') {
          item.show = true
        }
      })
    }
    tableInfo.value.data = []
  },
  {
    immediate: true,
    deep: true,
  }
)
watch(
  () => formInfo.value.data.deptId,
  (val) => {
    tableInfo.value.data = []
  },
  {
    immediate: true,
    deep: true,
  }
)
watch(
  () => formInfo.value.data.amortizationMethod,
  (val) => {
    if (!tableInfo.value.data.length) return
    setTableDataAmortizationRate()
  },
  {
    immediate: true,
    deep: true,
  }
)
watch(
  () => tableInfo.value.data.length,
  (val) => {
    if (!val) return
    setTableDataAmortizationRate()
  },
  {
    immediate: true,
    deep: true,
  }
)

onMounted(() => {
  if (props.orderId) {
    getMain()
  }
})

function setTableDataAmortizationRate(rate) {
  const tableLength = tableInfo.value.data.length
  if (formInfo.value.data.analysisType == 0) {
    tableInfo.value.data[0].amortizationRate = 100
    return
  }
  if (formInfo.value.data.amortizationMethod == 0) {
    tableInfo.value.data.forEach((item) => {
      item.amortizationRate = (100 / tableLength).toFixed(2) - 0
    })
    settingLastPrecision()
  } else if (formInfo.value.data.amortizationMethod == 1) {
    let rateCount = 0
    tableInfo.value.data.forEach((item, index) => {
      item.amortizationRate = item.primitiveOriginalAmount || 0
      rateCount += item.primitiveOriginalAmount
    })
    if (rateCount) {
      const multipleRate = 100 / rateCount
      tableInfo.value.data.forEach((item, index) => {
        item.amortizationRate =
          (item.amortizationRate * multipleRate).toFixed(2) - 0
      })
      settingLastPrecision()
    }
  }
}
function settingLastPrecision() {
  let rateCount = 0
  let exceptLatRateCount = 0
  const tableLength = tableInfo.value.data.length
  tableInfo.value.data.forEach((item, index) => {
    rateCount += item.amortizationRate
    if (index < tableLength - 1) {
      exceptLatRateCount += item.amortizationRate
    }
  })
  if (rateCount !== 0 && rateCount !== 100) {
    tableInfo.value.data[tableLength - 1].amortizationRate =
      (100 - exceptLatRateCount).toFixed(2) - 0
  }
}
function allSetting() {
  const obj = formFilter.value
  tableInfo.value.data.forEach((item) => {
    for (let k in obj) {
      if (obj[k] || obj[k] == 0) {
        item[k] = obj[k]
      }
    }
  })
  proxy.$refs.tableForm.clearValidate()
}
function checkDeptName() {
  useDeptInfo.value.visible = true
}
function callbackUseDept(data) {
  if (data && data.id) {
    formInfo.value.data.deptName = data.name
    formInfo.value.data.deptId = data.id
  } else {
    formInfo.value.data.deptName = ''
    formInfo.value.data.deptId = -2
  }
}
function getMain() {
  getAnalysisPlanById(props.orderId).then((res) => {
    if (res && res.success) {
      formInfo.value.data = res.data
      getAnalysisPlanDetailById({
        analysisPlanId: props.orderId,
      }).then((res) => {
        if (res && res.success) {
          tableInfo.value.data = res.data
        }
      })
    }
  })
}
function changeValidate(value, str, ref) {
  setTimeout(() => {
    proxy.$refs[ref].clearValidate(str)
  }, 30)
}
function tableRowClassName({ row = undefined }) {
  if (row.isChoice) {
    return 'success-row'
  } else {
    return ''
  }
}

// 触发事件
function handleEvent(event, data) {
  switch (event) {
    case 'tableCheck':
      tableInfo.value.selections = [...data]
      break
  }
}
function save() {
  if (tableInfo.value.data && tableInfo.value.data.length === 0) {
    proxy.$message.warning('请添加设备！')
    return
  }
  formInfo.value.ref.validate((valid) => {
    if (valid) {
      proxy.$refs.tableForm.validate((valid2) => {
        if (valid2) {
          const api = props.orderId ? putAnalysisPlan : postAnalysisPlan
          const data = formInfo.value.data
          data.details = tableInfo.value.data
          api(data).then((res) => {
            if (res && res.success) {
              showDialog.value = false
              proxy.$emit('returnModify', false)
            }
          })
        } else {
          proxy.$message.warning('请按照提示输入正确数据')
        }
      })
    } else {
      proxy.$message.warning('请按照提示输入正确数据')
    }
  })
}

//选择资产
function addAsset() {
  if (tableInfo.value.data.length) {
    selectAssetInfo.value.query.queryMap.id.value = tableInfo.value.data
      .map((item) => item.assetId)
      .toString()
  } else {
    selectAssetInfo.value.query.queryMap.id.value = ''
  }
  if (formInfo.value.data.analysisType == 0) {
    selectAssetInfo.value.checkBox = false
  } else {
    selectAssetInfo.value.checkBox = true
  }
  selectAssetInfo.value.query.queryParams.deptId = formInfo.value.data.deptId
  selectAssetInfo.value.query.queryParams.analysisPlanIdNotIn = props.orderId
  selectAssetInfo.value.visible = true
}
function callBackAsset(data) {
  if (formInfo.value.data.analysisType == 0) {
    data.assetId = data.id
    tableInfo.value.data = [data]
  } else {
    data.forEach((item) => {
      item.assetId = item.id
    })
    tableInfo.value.data = data.concat(tableInfo.value.data)
  }
}
//删除资产
function removeAsset(selectRow = undefined) {
  if (selectRow) {
    tableInfo.value.data = tableInfo.value.data.filter(
      (row) => row !== selectRow
    )
  } else {
    proxy
      .$confirm('删除后将改变数据,是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
      .then(() => {
        tableInfo.value.data = tableInfo.value.data.filter(
          (row) => !tableInfo.value.selections.includes(row)
        )
      })
  }
}
</script>

<style scoped lang="scss">
:deep(.page-table) > .el-table {
  overflow: hidden;
}
:deep(.model-panel-body) .filter-item {
  .el-form-item--default.el-form-item {
    margin-top: 6px;
    margin-bottom: 6px;
  }
}
</style>
